package com.javabase.y2022.m05.day0516.v06;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;

/**
 * @descriptions:
 * @author: Tom
 * @date: 2022/5/16 下午 02:33
 * @version: 1.0
 */
public class Solution {
    // 如何使用棧來實現隊列?
    // 应该是需要准备两个栈，一个栈需要存储进来的数，一个栈用来存储被push的数字
    public static class QueueByTwoStacks {
        Stack<Integer> popStack;
        Stack<Integer> pushStack;

        public QueueByTwoStacks() {
            this.popStack = new Stack<>();
            this.pushStack = new Stack<>();
        }

        public void pushToPop() {
            if (popStack.isEmpty()) {
                while (!pushStack.empty()) {
                    popStack.push(pushStack.pop());
                }
            }
        }

        public void add(int value){
            this.pushStack.push(value);
            this.pushToPop();
        }

        public int remove(){
            this.pushToPop();
            if(this.popStack.isEmpty()){
                throw new RuntimeException("is empty.");
            }
            int ans = this.popStack.pop();
            return ans;
        }
    }
    // 如何使用隊列來實現棧
    public class MyStack04{
        Queue<Integer> queue;
        Queue<Integer> help;
        public MyStack04(){
            queue = new ArrayDeque<>();
            help = new ArrayDeque<>();
        }
        public int pop(){
            while(queue.size() > 1){
                help.offer(queue.poll());
            }
            int ans = queue.poll();
            Queue<Integer> tmp = queue;
            queue = help;
            help = tmp;
            return ans;
        }
        public void push(int value){
            this.queue.offer(value);
        }
        public int peek(){
            while(queue.size() > 1){
                help.offer(queue.poll());
            }
            int ans = queue.poll();
            queue.offer(ans);
            Queue<Integer> tmp = queue;
            queue = help;
            help = tmp;
            return ans;
        }
    }


}
